// pages/shop_coupon/index.js
import {navTo,navToTab,onInput,onClick,showText} from '../../utils/reuse'
import{ addCard ,cardList,card_stop,addTicket,addTicketList,addTicketDdit} from '../../api/index'
import {formatTime} from '../../utils/util'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import {baseURL} from '../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list:[],

    add_coupon:false,
    checked:false,

    time_show:false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),

    form:{
      name:'',
      price:'',
      type:1,
    },
    page:1,
    pagesize:10,
    page_show:true,
    page_text:'加载中...',
    fileList: [],
    fileUrl:[],
  },
  getCardList(){
    var obj = {
      uid:wx.getStorageSync('uid'),
      shop_id:wx.getStorageSync('shop_id'),
      page:this.data.page,
      pagesize:this.data.pagesize,
    }
    addTicketList(obj).then(res=>{
      if(res.msg.length <= 0){
        return this.setData({
          page_show:false,
          page_text:'加载完毕！'
        })
      }
      if(res.sta == 1){
        if(res.msg.length < this.data.pagesize){
          this.setData({
            page_show:false,
            page_text:'加载完毕！'
          })
        }
        res.msg.forEach(item=>{
          var arr = []
          if(item.images){
            var arr1 = []
            arr = item.images.split(',')
            arr.forEach(item=>{
              arr1.push(baseURL + item)
            })
            item.images = arr1
          }
        })
        this.setData({
          list:[...this.data.list,...res.msg]
        })
      }
    })
  },
  submit(){
    var images = ''
    if(this.data.fileUrl.length !== 0){
      var arr = []
      this.data.fileUrl.forEach((item)=>{
        arr.push(item.url)
      })
      images = arr.join(',')
    }
    var obj = {
      shop_id:wx.getStorageSync('shop_id'),
      uid:wx.getStorageSync('uid'),
      name:this.data.form.name,
      price:this.data.form.price,
      type:this.data.form.type,
      images
    }
    addTicket(obj).then(res=>{
      if(res.sta == 1){
        showText(res.msg,1)
        this.setData({
          page:1,
          pagesize:this.data.pagesize,
          page_show:true,
          list:[]
        })
        this.getCardList()
        this.setData({
          add_coupon:false,
          form:{
            name:'',
            price:'',
            type:1
          },
          fileUrl:[],
          fileList:[]
        })
      }else{
        showText(res.msg,2)
      }
    })
  },
  PariceChange(e){
    this.setData({
      'form.price': this.money(e.detail)
    })
  },
  money(val) {
    let num = val.toString(); //先转换成字符串类型
    if (num.indexOf('.') == 0) { //第一位就是 .
      num = '0' + num
    }
    num = num.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
    num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    if (num.indexOf(".") < 0 && num != "") {
      num = parseFloat(num);
    }
    return num
  },
  cancel(e){
    this.setData({
      form:{
        name:'',
        price:'',
        type:1
      },
      fileUrl:[],
      fileList:[],
      add_coupon:false
    })
  },
  time_confirm(e){
    this.setData({
      time_show:false,
      'form.time':formatTime(new Date(e.detail))
    })
  },

  time_cancel(e){
    this.setData({
      time_show:false
    })
  },
  click(e){
    onClick(e,this)
  },
  change(e){
    onInput(e,this)
  },
  removeFn(e){
    Dialog.confirm({
      title: '确定要删除吗？'
    })
      .then((res) => {
        const id = e.currentTarget.dataset.id
        var obj = {
          uid:wx.getStorageSync('uid'),
          ticket_id:id,
        }
        addTicketDdit(obj).then(res=>{
          if(res.sta == 1){
            showText('删除成功！',1)
            this.setData({
              page:1,
              pagesize:this.data.pagesize,
              page_show:true,
              list:[]
            })
            this.getCardList()
          }else{
            showText('删除失败！',2)
          }
        })
      })
      .catch((res) => {
        console.log(res)
      });
  },
  deleteFn(e){
    var num1 = this.data.fileList.splice(1,e.detail.index)
    var num2 = this.data.fileUrl.splice(1,e.detail.index)
    this.setData({
      fileList:num1,
      fileUrl:num2,
    })
  },
  // 上传
  afterRead(event) {
    const that = this
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: 'https://horse.molijuhe.com/api/common/upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success(res) {
        var data = JSON.parse(res.data)
        // 上传完成需要更新 fileList
        const fileList = that.data.fileList
        fileList.push({ url: data.data.fullurl });
        const fileUrl = that.data.fileUrl
        fileUrl.push({ url: data.data.url });
        that.setData({ fileList,fileUrl });
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      page:1,
      pagesize:this.data.pagesize,
    })
    this.getCardList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page:1,
      pagesize:this.data.pagesize,
      page_show:true,
      list:[]
    })
    this.getCardList()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      page:this.data.page+1,
    })
    if(this.data.page_show){
      this.getCardList()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})